package com.ranga.mselfcare;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ranga.mselfcare.config.Config;
import com.ranga.mselfcare.services.LoginService;

@SuppressLint("HandlerLeak")
public class LoginActivity extends Activity implements OnClickListener {

	private EditText txtPhoneNumber;
	private EditText txtToken;
	private Button btnSignIn;
	private String token = "", phoneNumber = "";
	private static final String TAG = "LoginActivity";
	private int status = Config.PROGRESS_STOPPED;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		txtPhoneNumber = (EditText) findViewById(R.id.et_phoneNumber);
		txtToken = (EditText) findViewById(R.id.et_token);
		btnSignIn = (Button) findViewById(R.id.b_signIn);

		btnSignIn.setOnClickListener(this);
		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);

		initializeDataFromSharedPreference();
		setDataFileds();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		hideProgressDialog();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (status == Config.PROGRESS_STARTED) {
			progressDialog.show();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Config.STATUS, status);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		status = savedInstanceState.getInt(Config.STATUS);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.b_signIn:
			if (validateFields()) {
				if (isNetworkAvailable()) {
					if (status == Config.PROGRESS_STOPPED) {
						token = txtToken.getText().toString();
						phoneNumber = txtPhoneNumber.getText().toString();
						Intent intent = new Intent(LoginActivity.this,
								LoginService.class);
						Messenger resultMessenger = new Messenger(
								serviceResultHandler);
						Messenger progressMessenger = new Messenger(
								progressHandler);
						Bundle bundle = new Bundle();
						bundle.putString(Config.PHONE_NUMBER, phoneNumber);
						bundle.putString(Config.TOKEN, token);
						try {
							Log.w(TAG, "inside try");
							intent.putExtras(bundle);
							intent.putExtra(Config.RESULT_MESSENGER,
									resultMessenger);
							intent.putExtra(Config.PROGRESS_MESSENGER,
									progressMessenger);
							startService(intent);
						} catch (SecurityException e) {
							Log.w(TAG, "Unable to start get login service: "
									+ e.toString());
						}

					}
				}
			}
			break;
		}

	}

	private boolean validateFields() {
		String phoneNumber = txtPhoneNumber.getText().toString();
		String token = txtToken.getText().toString();
		boolean verified = false;
		if (phoneNumber != null) {
			if (!phoneNumber.trim().isEmpty()) {
				if (token != null) {
					if (!token.trim().isEmpty()) {
						verified = true;
					} else {
						verified = false;
						showToast(R.string.alert_need_to_enter_token);
						txtToken.setFocusable(true);
						txtToken.requestFocus();
					}
				} else {
					verified = false;
					showToast(R.string.alert_need_to_enter_token);
					txtToken.setFocusable(true);
					txtToken.requestFocus();
				}

			} else {
				verified = false;
				showToast(R.string.alert_need_to_enter_phone_number);
				txtPhoneNumber.setFocusable(true);
				txtPhoneNumber.requestFocus();
			}
		} else {
			verified = false;
			showToast(R.string.alert_need_to_enter_phone_number);
			txtPhoneNumber.setFocusable(true);
			txtPhoneNumber.requestFocus();
		}

		return verified;
	}

	private void showToast(int message) {
		Toast.makeText(this, LoginActivity.this.getString(message), Toast.LENGTH_SHORT).show();
	}

	private void initializeDataFromSharedPreference() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		token = prefs.getString(Config.TOKEN, "");
		phoneNumber = prefs.getString(Config.PHONE_NUMBER, "");

		if (token.contentEquals("")) {
			Log.e(TAG, "token not saved from previous activity");
			AlertDialog.Builder alertTokenNotRecieved = new AlertDialog.Builder(
					this);
			alertTokenNotRecieved.setTitle(this.getString(R.string.alert));
			alertTokenNotRecieved
					.setMessage(getString(R.string.alert_token_not_saved));
			alertTokenNotRecieved.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startTokenInitializeActivity();
						}
					});
		}
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder alertExit = new AlertDialog.Builder(this);
		alertExit.setTitle(getString(R.string.alert));
		alertExit.setMessage(getString(R.string.alert_exit));
		alertExit.setPositiveButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();

					}
				});
		alertExit.setNegativeButton(getString(R.string.no),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

					}
				});
		alertExit.show();
	}

	private void setDataFileds() {
		txtToken.setText(token);
		txtPhoneNumber.setText(phoneNumber);
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		boolean networkAvailable = false;

		if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
			networkAvailable = true;
		} else {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setTitle(getString(R.string.alert));
			alertDialog
					.setMessage(getString(R.string.no_internet_connectivity));
			alertDialog.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(
									WifiManager.ACTION_PICK_WIFI_NETWORK));
						}
					});
			alertDialog.show();
		}
		return networkAvailable;
	}

	private Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {

			status = message.arg1;

			switch (status) {

			case Config.PROGRESS_STARTED:
				Log.i(TAG, "Progress Started");
				progressDialog.setMessage(LoginActivity.this
						.getString(R.string.login_in));
				progressDialog.show();
				status = Config.PROGRESS_STOPPED;
				break;
			case Config.PROGRESS_STOPPED:
				Log.i(TAG, "Progress stopped");
				hideProgressDialog();
				showToast(R.string.alert_login_failed);
				status = Config.PROGRESS_STOPPED;
				break;
			case Config.PROGRESS_SUCCESS:
				Log.i(TAG, "Progress success");
				hideProgressDialog();
				status = Config.PROGRESS_STOPPED;
				break;
			}
		};
	};

	private Handler serviceResultHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle resultBundle = message.getData();
			int responseError = 0;
			if (resultBundle.containsKey(Config.RESPONSE_ERROR)) {
				responseError = Integer.parseInt(resultBundle.getString(Config.RESPONSE_ERROR));
			}
			Log.w(TAG, "Response Recieved: " + responseError);

			if (responseError == 200) {
				Intent intent = new Intent(LoginActivity.this, MainMenuActivity.class);
				finish();
				startActivity(intent);
				
			} else if (responseError == 405){
				showToast(R.string.alert_token_expired);
				startTokenInitializeActivity();
			} else if (responseError == 403) {
				displayErrorMessage(R.string.alert_invalid_subscriber);
				status = Config.PROGRESS_STOPPED;
			} else {
				displayErrorMessage(R.string.alert_login_failed);
				status = Config.PROGRESS_STOPPED;
			}
		};
	};

	private void displayErrorMessage(int message) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				LoginActivity.this);
		alertDialog.setTitle(getString(R.string.alert));
		alertDialog.setMessage(getString(message));
		alertDialog.setPositiveButton(getString(R.string.okay),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alertDialog.show();
	}

	private void hideProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	private void startTokenInitializeActivity() {
		Intent tokenInitialize = new Intent(LoginActivity.this, TokenInitializeActivity.class);
		finish();
		startActivity(tokenInitialize);
	}

}
